package com.xhq.netty.io;

import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

public class BlockIO {
    public static void BIO() throws Exception {
        var serverSocket = new ServerSocket(9090);
        System.out.println("start server at port:9090");

        var client = serverSocket.accept();
        System.out.println("accept client, port:" + client.getPort());

        var clientInput = client.getInputStream();
        var bf = new BufferedReader(new InputStreamReader(clientInput));
        var line = bf.readLine();
        while (!StringUtils.isBlank(line)){
            System.out.println(line);
            line = bf.readLine();
        }
    }

    public static void BIOOneThreadPerConnect() throws Exception {
        var sockerServer = new ServerSocket(9090);
        System.out.println("server start at 9090");
        while (true){
            var client = sockerServer.accept();
            System.out.println("accept client " + client.getPort());
            new Thread(() -> {
                readMessage(client);
            }).start();
        }
    }

    private static void readMessage(Socket client) {
        try {
            var clientInput = client.getInputStream();
            var bf = new BufferedReader(new InputStreamReader(clientInput));
            var line = bf.readLine();
            while (!StringUtils.isBlank(line)){
                System.out.println(line);
                line = bf.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
